package com.example.demo.config;

import com.example.demo.entity.config.CustomeParam;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {

    private final InterceptorConfig interceptorConfig;
    private final CustomeParam param;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 实现跨域
        // 取消跨域：allowCredentials(false) 与 allowedOrigins("*")
        // 1、指哪些接口URL需要增加跨域设置
        // 2、需要带cookie等凭证时，设置为true，就会把cookie的相关信息带上
        // 3、指前端哪些域名被允许跨域，负载均衡时只需填负载均衡的IP:Port
        // 4、指允许哪些类型的方法
        // 5、cookie的失效时间，单位为秒（s），若设置为-1，则关闭浏览器就失效
        registry.addMapping("/**")
                .allowCredentials(!param.isUseTestMode())
                .allowedOrigins(param.isUseTestMode() ? "*" : param.getCrossDomain())
                .allowedMethods("GET", "POST")
                .maxAge(1800);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册拦截器(写入自定义的拦截器类)
        InterceptorRegistration registration = registry.addInterceptor(interceptorConfig);
        registration.addPathPatterns("/**");
    }
}
